<template>
  <el-card>
    <el-tabs v-model="activeName" @tab-click="changeTable">
      <el-tab-pane label="基本信息" name="basicInfo">
        <editProductBasic ref="basicInfo" :form="form"></editProductBasic>
      </el-tab-pane>
      <el-tab-pane label="规格信息" name="attributeInfo">
        <editProductAttribute ref="attributeInfo" :productAttributeList="productAttributeList"></editProductAttribute>
      </el-tab-pane>
      <el-tab-pane label="sku信息" name="skuInfo">
        <editProductSku ref="skuInfo" :productSkuList="productSkuList"></editProductSku>
      </el-tab-pane>
    </el-tabs>
    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm()">保存</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getProduct, addProduct, updateProduct } from "@/api/supermarket/product";

import editProductBasic from "./editProductBasic.vue";
import editProductAttribute from "./editProductAttribute.vue";
import editProductSku from "./editProductSku.vue";

export default {
  name: "ProductEdit",
  components: {
    editProductBasic,
    editProductAttribute,
    editProductSku
  },
  data () {
    return {
      //默认false添加，true修改
      productUpdate: false,
      // 选中选项卡的 name
      activeName: "basicInfo",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 商品属性列表
      productAttributeList:[],
      // 商品规格列表
      productSkuList: [],
    };
  },

  watch:{         
    productAttributeList(newVal,oldVal){                   
      //newVal：表示改变后的值，即第一个形参，不要调换位置。
      //oldVal：表示改变前的值，
      console.log("观察新"+newVal);
      console.log("观察老"+oldVal);
      this.skuTableData();
    }
  },

  created () {
    const productId = this.$route.params && this.$route.params.productId;
    if (productId == 0) {
      this.productUpdate=false;
      this.productAttributeList = [{
        "id": Math.random(),
        "title": "默认",
        "inputList": "无",
        "type": 0,
        "sort": 0
      }];
      return;
    }else{
      this.productUpdate=true;
      getProduct(productId).then(response => {
        this.form = response.data.product;
        this.productAttributeList = response.data.productAttributeList;
        this.productSkuList = response.data.productSkuList;
        //加载默认sku数据
        this.skuTableData();
      });
    }
  },
  methods: {
    //切换tab页事件
    changeTable(tab, event) {
      if(tab.index == 1){
        this.$refs.attributeInfo.attributeTableMove();
      }else if(tab.index == 2){
        this.skuTableData();
      }
      console.log("切换"+tab);
      console.log("切换"+event);
    },

    //初始化sku数据
    skuTableData(){

      let row  = [];

      for(let i=0;i<this.productAttributeList.length;i++){
        let attr = this.productAttributeList[i];
        
        let title = attr.title;
        let inputList  = attr.inputList.split(/[\n\s+,，；;]/g);

        let col = [];
        inputList.forEach(input => {
          if(input == ""){
            return;
          }
          col.push(title+":"+input);
        });

        row.push(col);
      }
      //console.log(JSON.stringify(row));

      let res  = row.reduce((prev,cur) => {
        const emptyVal = [];
        prev.forEach(val => {
          cur.forEach(item => {
            emptyVal.push(val+";"+item);
          })
        })
        return emptyVal;
      });
      console.log(res);
      //生成Sku表格数据
      let skuList = [];
      
      for(let i = 0 ; i < res.length; i++){
        let sku = {
          code : i+1,
          spData : res[i]
        };

        for(let j = 0 ; j < this.productSkuList.length; j++){
          let ps = this.productSkuList[j];
          if(ps.spData == res [i]){
            sku = ps;
            sku.code= ps.skuCode || (j+1);
          }
        }
        
        skuList.push(sku);
      }

      this.productSkuList = skuList;
      },
    //---------------------------------------------------------------------------

    /** 提交按钮 */
    submitForm () {
      const basicForm = this.$refs.basicInfo.$refs.form;
      
      Promise.all([basicForm].map(this.getFormPromise)).then(res => {
        const validateResult = res.every(item => !!item);
        if (validateResult) {
        
          let data = {
            product: this.form,
            productAttributeList: this.productAttributeList,
            productSkuList : this.productSkuList
          }

          //是否为修改
          if(this.productUpdate){
            updateProduct(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              if (response.code == 200) {
                this.close();
              }
            });
          }else{
            addProduct(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              if (response.code == 200) {
                this.close();
              }
            });
          }
          

        } else {
          this.$modal.msgError("表单校验未通过，请重新检查提交内容");
        }
      });
    },
    getFormPromise (form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },

    /** 关闭按钮 */
    close () {
      const obj = { path: "/supermarket/products/product", query: { t: Date.now(), pageNum: this.$route.query.pageNum } };
      this.$tab.closeOpenPage(obj);
    },
  },

};
</script>
